import axios from 'axios';
import store from '@/store';
import { getToken } from '@/utils/auth';
import { message } from 'ant-design-vue';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url

  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    const icode = '325DEE90E25A32A4';
    if (config.method === 'get') {
      config.params = { ...config.params, icode };
    } else {
      config.data = { ...config.data, icode };
    }
    if (store.getters.token) {
      config.headers['Authorization'] = `Bearer ${getToken()}`;
    }
    return config;
  },
  (error) => {
    // do something with request error

    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    /**
     * 下面的注释为通过在response里，自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题，登出并返回到登录页
     * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
     * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
     */
    const data = response.data;
    if (data.code === 0) {
      return data.data;
    } else {
      message.error(data.error);
    }
  },
  (error) => {
    console.log('[error]', error.response); // for debug
    const { data } = error.response;
    message.error(data.error);
    return Promise.reject(error);
  }
);

export default service;
